package com.dqp.cslggroup.Util;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class verification {


    public static Map<String, String> digitalSignature(int kinds) {
        long myTimestamp = System.currentTimeMillis()/1000;//秒
        String randomString = getRandomString(8);
        String result = getMd5Value(getSha1(myTimestamp + "84A1FF2F39CC14B9" + randomString)).toUpperCase();
        Map<String, String> map = new HashMap<>();
        map.put("client_id", String.valueOf(myTimestamp));
        map.put("client_secret", randomString);
        map.put("client_token", result);
        map.put("function", kinds+"");
        return map;
    }


    //length用户要求产生字符串的长度
    private static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    private static String getSha1(String str) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes(StandardCharsets.UTF_8));
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }

    private static String getMd5Value(String value) {
        try {
            //1. 获得md5加密算法工具类
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            //2. 加密的结果为十进制
            byte[] md5Bytes = messageDigest.digest(value.getBytes());
            //3. 将md5加密算法值转化为16进制
            BigInteger bigInteger = new BigInteger(1, md5Bytes);
            return bigInteger.toString(16);

        } catch (Exception e) {
            //如果产生错误则抛出异常
            throw new RuntimeException();
        }
    }


}
